package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"net/http"
)

type Order struct {
	OrderId           int64 `gorm:"primaryKey"`
	AccumulativeTotal float64
}

func (Order) TableName() string {
	return "t_order"
}

// 更新丢失 代码
func main() {
	//建立mysql连接
	dsn := "root:mWwdsqw1s2x3x*@tcp(mysql3:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Println("mysql数据库连接失败,", err.Error())
		return
	}
	//创建gin路由
	r := gin.Default()
	r.GET("/update", func(c *gin.Context) {
		//开启事务
		tx := db.Begin()
		var order Order
		tx.Raw("select order_id, accumulative_total from t_order where order_id = ?", 1).Scan(&order)
		//内存中加一后更新
		tx.Exec("update t_order set accumulative_total = ? where order_id = ?", order.AccumulativeTotal+1.0, 1)
		//提交
		tx.Commit()
		c.JSON(http.StatusOK, gin.H{
			"message": "ok",
		})
	})
	r.Run(":8080") // 监听并在 0.0.0.0:8080 上启动服务
}
